import { reqGetUserImgById, reqGetUserInfo, reqLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const state = {
  token: getToken() || '',
  userInfo: {}
}
const mutations = {
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(context, loginForm) {
    const { data: { data }} = await reqLogin(loginForm)
    console.log(data)
    context.commit('setToken', data)
  },
  async getUserInfo(context) {
    const { data: { data }} = await reqGetUserInfo()
    // console.log(data)
    const { data: { data: data1 }} = await reqGetUserImgById(data.userId)
    const res = { ...data, ...data1 }
    context.commit('setUserInfo', res)
    return res
  },
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
